package com.example.zwh.uilayouttest;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private List<Msg> msgList = new ArrayList<>();
    private EditText inputText;
    private Button send;
    private RecyclerView msgRecyclerView;



    private MsgAdapter adapter;

    private Socket socket = null;
    //主线程
    private Handler handler = null;

    //
    private String content = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initMsgs();
        inputText = (EditText) findViewById(R.id.input_text);
        send = (Button) findViewById(R.id.send);
        msgRecyclerView = (RecyclerView) findViewById(R.id.msg_recycle_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        msgRecyclerView.setLayoutManager(layoutManager);
        adapter = new MsgAdapter(msgList);
        msgRecyclerView.setAdapter(adapter);

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                String str = msg.getData().getString("str");
                Msg msg_ = new Msg(str, Msg.TYPE_RECEIVED);
                msgList.add(msg_);
                adapter.notifyItemInserted(msgList.size() - 1);
                msgRecyclerView.scrollToPosition(msgList.size() - 1);
            }
        };

        (new Thread(new connectThread())).start();


        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                content = inputText.getText().toString();
                if (!"".equals(content)) {
                    Msg msg = new Msg(content, Msg.TYPE_SENT);
                    msgList.add(msg);
                    System.out.println("Send: " + content);

                    adapter.notifyItemInserted(msgList.size() - 1);
                    msgRecyclerView.scrollToPosition(msgList.size() - 1);

                    inputText.setText("");
                    (new Thread(new sendTread())).start();
                }
            }
        });



    }

    class sendTread implements Runnable {
        @Override
        public void run() {
            try {
                send(content);
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    class connectThread implements Runnable {

        @Override
        public void run() {
            try {
                MainActivity.this.socket = new Socket("39.108.12.42", 9050);
                System.out.println("连接成功!");
                (new Thread(new ReceiveThread())).start();
            }catch (Exception e) {
                e.printStackTrace();
                System.out.println("连接失败...");
            }
        }
    }

    private void initMsgs() {
        Date day=new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(df.format(day));
        Msg msg1 = new Msg(df.format(day), Msg.TYPE_RECEIVED);
        msgList.add(msg1);
    }

    public void send(String str) throws Exception {
        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
        dos.writeUTF(str);
    }

    class ReceiveThread implements Runnable {
        public void run() {

            if (socket == null) return;
            try {
                System.out.println("正在接收...");
                DataInputStream dis = new DataInputStream(socket.getInputStream());
                String str = null;
                while (true) {
                    str = dis.readUTF();
                    System.out.println("Receive: " + str);
                    Message message = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putString("str", str);
                    message.setData(bundle);//bundle传值，耗时，效率低
                    handler.sendMessage(message);//发送message信息

//                    Msg msg = new Msg(str, Msg.TYPE_RECEIVED);
//                    msgList.add(msg);
//
//                    adapter.notifyItemInserted(msgList.size() - 1);
//                    msgRecyclerView.scrollToPosition(msgList.size() - 1);

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
